pub use crate::error::CommonError;


/*
let s = Stream::new();
for iter in  s.iter_from(0) {
}

pub struct StreamIterator {
}
pub trait Stream  {
    fn append(&mut self, bytes: &[u8]) -> Result<usize, CommonError>;
    fn size(&self) -> usize;
    fn iter_from(&self, from: usize) -> StreamIterator ;
}
// fn erase(&mut self, start: usize, len: usize) -> Result<usize, CommonError>;
// fn write(&mut self, from: &[u8], to: usize) -> Result<usize, CommonError>;
// fn read(&self, from: usize, to: &mut &[u8]) -> Result<usize, CommonError>;
*/


#[derive(Debug)]
pub struct MemStream {
    id: String,
    content: Vec<u8>
}

impl MemStream {
    pub fn new(id: &str) -> Self {
        Self {
            id: String::from(id),
            content: Vec::new()
        }
    }
}
impl MemStream {
    pub fn append(&mut self, bytes: &[u8]) -> Result<usize, CommonError>{
        self.content.extend_from_slice(bytes);
        Ok(bytes.len())
    }
    pub fn erase(&mut self, _start: usize, _len: usize) -> Result<usize, CommonError>{
        //TODO:
        Ok(0)
    }
    pub fn write(&mut self, from: &[u8], _to: usize) -> Result<usize, CommonError>{
        //TODO: check override? 
        //TODO: write body
        //Ok(0)
        self.append(from)
    }
    pub fn read(&self, _from: usize, _to: &mut &[u8]) -> Result<usize, CommonError>{
        //TODO:
        Ok(0)
    }
    pub fn size(&self) -> usize {
        self.content.len()
    }
    pub fn id(&self) -> &str {
        &self.id
    }
}

#[cfg(test)]
mod test {
    use super::*;
    #[test]
    fn test_new(){
        let ms = MemStream::new("ms_1");
        assert_eq!("ms_1", ms.id.as_str());
        assert_eq!(0, ms.content.len());
    }
    #[test]
    fn test_size(){
        let ms = MemStream::new("ms_1");
        assert_eq!(0, ms.size());
    }
    #[test]
    fn test_append(){
        let mut ms = MemStream::new("ms_1");
        let hello = "hello".as_bytes();
        assert_eq!(hello.len(), ms.append(hello).unwrap());

        let world = " world ".as_bytes();
        assert_eq!(world.len(), ms.append(world).unwrap());

        assert_eq!(hello.len() + world.len(), ms.size());
    }

    #[test]
    fn test_write(){
        let mut ms = MemStream::new("ms_1");
        let hello = "hello".as_bytes();
        assert_eq!(hello.len(), ms.write(hello, ms.size()).unwrap());
        assert_eq!(hello.len(), ms.size());
    }
}
